package go_common

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)
type BaseModel struct {
	Id int64 `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id,omitempty" `
	CreatedAt MyTime `json:"created_at,omitempty"`
	UpdatedAt MyTime `json:"updated_at,omitempty"`
	DeletedAt *MyTime `gorm:"DEFAULT:NULL" json:"deleted_at,omitempty"`
}
type CommModel struct {
	Id int64 `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id,omitempty" `
	CreatedAt MyTime `json:"created_at,omitempty"`
	UpdatedAt MyTime `json:"updated_at,omitempty"`
}

var db *gorm.DB

func InitDb(url, prefix string, maxIdleConns, maxOpenConns int, enableLog bool, models ...interface{}) error {
	return  openDb("mysql", url, prefix, maxIdleConns, maxOpenConns, enableLog, models...)
}
func openDb(dialect string, url, prefix string, maxIdleConns, maxOpenConns int, enableLog bool, models ...interface{})  (err error) {
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		if prefix != "" {
			return prefix + "_" + defaultTableName
		}
		return  defaultTableName
	}
	if db, err = gorm.Open(dialect, url); err != nil {
		return
	}
	db.LogMode(enableLog)
	db.SingularTable(true)
	db.DB().SetMaxIdleConns(maxIdleConns)
	db.DB().SetMaxOpenConns(maxOpenConns)
	if err = db.AutoMigrate(models...).Error; err != nil {
		return err
	}
	return
}

func GetDb() *gorm.DB  {
	return  db
}
func CloseDb() {
	if db != nil {
		return
	}
	if err := db.Close(); err != nil {
		return
	}
}
// 事务
func Tx(db *gorm.DB, txFunc func(tx *gorm.DB) error) (err error) {
	tx := db.Begin()
	if tx.Error != nil {
		return
	}

	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			panic(r) // re-throw panic after Rollback
		} else if err != nil {
			tx.Rollback()
		} else {
			err = tx.Commit().Error
		}
	}()

	err = txFunc(tx)
	return err
}
